// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <pollux/buffer/buffer.h>

namespace kumo::pollux {
    /// Helper struct to lazily initialize nulls buffer on first null.
    struct NullsBuilder {
        NullsBuilder(vector_size_t size, memory::MemoryPool *pool)
            : size_{size}, pool_{pool} {
        }

        /// Marks specified row as null. Allocates and initializes null buffer if this
        /// is the first null.
        void set_null(vector_size_t row) {
            if (nulls_ == nullptr) {
                nulls_ = AlignedBuffer::allocate<bool>(size_, pool_, bits::kNotNull);
                rawNulls_ = nulls_->asMutable<uint64_t>();
            }
            bits::set_null(rawNulls_, row, true);
        }

        /// Returns nulls buffer or nullptr if no nulls were added (e.g. set_null was
        /// never called).
        BufferPtr build() const {
            return nulls_;
        }

    private:
        const vector_size_t size_;
        memory::MemoryPool *pool_;
        BufferPtr nulls_{nullptr};
        uint64_t *rawNulls_{nullptr};
    };
} // namespace kumo::pollux
